<?php

class Osml_Application_Plugin_Acces extends \Zend_Controller_Plugin_Abstract
{

    public function preDispatch (Zend_Controller_Request_Abstract $request)
    {
        // return true;
        if (! $this->_accessValid($request)) {
            // on lève une exception car le controller peut la gérer simplement
            throw new Zend_Acl_Exception(
                    sprintf(
                            __(
                                    "Vous n'avez pas accès à cette ressource '%s' - '%s'"), 
                            $request->getControllerName(), 
                            $request->getActionName()), '200');
        }
    }

    /**
     *
     * @return Osml_Acl
     */
    protected function getAcl ()
    {
        return Zend_Registry::get("acl");
    }

    protected function _accessValid (Zend_Controller_Request_Abstract $request)
    {
        $acl = $this->getAcl();
        $env = Jnd_App::getEnvironnement();
        
        $module = $request->getModuleName();
        $controller = $request->getControllerName();
        if ( strpos($controller, "-") !== false) {
            $tmp = explode("-", $controller);
            $controller = $tmp[0] . ucfirst($tmp[1]);
        }
        $action = $request->getActionName();
        
        $identite = Zend_Auth::getInstance()->getIdentity();
        if (is_null($identite)) {
            $role = "invite";
            $roles = array(
                    Back_Model_Roles::recuperationIdParValeur("invite")
            );
        } else {
            $roles = $env->getRoles();
        }
        
        $ressource = $module . "." . $controller;
        $rolesUtilisateurs = $env->getRoles();
        $flagAcces = false;
        
        foreach ($roles as $tmpRole) {
            $roleTexte = Back_Model_Roles::recuperationValeurParId($tmpRole);
            $flagAcces = $acl->isAllowed($roleTexte, $ressource) || $flagAcces;
//             Zend_Debug::dump(array($roleTexte, $ressource, $flagAcces));
            
            // on a les droits sur la ressource globale, on controle donc les
            // droits sur l'action
            $flagAcces = $acl->isAllowed($roleTexte, $ressource, $action) || $flagAcces;
//             Zend_Debug::dump(array($roleTexte, $ressource, $actions, $flagAcces));
        }
        
//         die($flagAcces);
        return $flagAcces;
    }
}

